from urllib import urlencode
from google.appengine.api import urlfetch, urlfetch_stub
from google.appengine.api import apiproxy_stub_map
import os
import xml.dom.minidom
from extensions import cspxml

auth_uri = 'https://www.google.com/accounts/ClientLogin'
host = 'http://cspshare.appspot.com'
target = host + '/rest/component'
app_name = 'CSPShare-1.0'
email = 'xxx@gmail.com'
passwd = 'xxx'

# init proxy for urlfetch
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
apiproxy_stub_map.apiproxy.RegisterStub('urlfetch',urlfetch_stub.URLFetchServiceStub())

# Get auth. token
authreq_data = urlencode({ "Email": email, "Passwd":  passwd, "service": "ah", "source": app_name, "accountType": "HOSTED_OR_GOOGLE" })
auth_result = urlfetch.fetch(auth_uri,authreq_data,method=urlfetch.POST)
auth_dict = dict([ x.split('=') for x in auth_result.content.split("\n") if (x) ])
auth_token = auth_dict["Auth"]

# Get auth. cookie
serv_args = {'auth': auth_token, 'continue': target}
serv_uri = "%s/_ah/login?%s" % (host, urlencode(serv_args))
cookie_result = urlfetch.fetch(serv_uri,follow_redirects=False,method=urlfetch.GET)
auth_cookie = cookie_result.headers['set-cookie'].split('=')
auth_cookie[1] = auth_cookie[1].strip('; expires')
cookie = {'name':auth_cookie[0], 'value':auth_cookie[1]}

# use cookie to access page
cookieHdr = {'Cookie' : cookie['name']+'='+cookie['value']}
#result = urlfetch.fetch(target,headers=headers,follow_redirects=False)
#file = open('/Users/epb/Documents/uni/kandidat/1aar/cspshare/code/CSPBuilder/Components/Mandelbrot.py')
#content = file.read().encode('base64')
#print content
#data = '<componentcode><code>'+content+'</code><name>Mandelbrot.py</name></componentcode>'
#data = '<component><name>Testing.csp</name></component>'
#result = urlfetch.fetch(target, data, urlfetch.POST, headers, follow_redirects=False)

#doc = xml.dom.minidom.Document()
#compElem = doc.createElement("component")
#commentElem = doc.createElement("comment")
#contentElem = doc.createElement("content")
#usersElem = doc.createElement("users")
#nameElem = doc.createElement("name")
#name = doc.createTextNode('Some name')
#nameElem.appendChild(name)
#compElem.appendChild(commentElem)
#compElem.appendChild(contentElem)
#compElem.appendChild(usersElem)
#compElem.appendChild(nameElem)
#doc.appendChild(compElem)

# Print our newly created XML
#print doc.toprettyxml(indent="  ")

doc = cspxml.getCompXMLDoc('Some other name', 'Some comment', content='Some content')
result = urlfetch.fetch(target, doc, urlfetch.POST, cookieHdr, follow_redirects=False)
print result.content

#print result.content

#result = urlfetch.fetch(host+'/rest/componentcode/aghjc3BzaGFyZXIUCxINQ29tcG9uZW50Q29kZRjUDww', headers=headers, follow_redirects=False)
#dom = xml.dom.minidom.parseString(result.content)
#for e in dom.getElementsByTagName('code'):
#    print e.firstChild.nodeValue + '\n'
#    print e.firstChild.nodeValue.decode('base64')


############################################################################
############################################################################

from google.appengine.tools import appengine_rpc
#from google.appengine.api import urlfetch, urlfetch_stub
#
#import urllib2, cookielib
#from urllib import urlencode
#import cgi
#import logging
#import logging.handlers
#
#
#loggerName = 'google.appengine.tools.appengine_rpc'
#LOG_FILENAME = '/tmp/log.out'
#host = 'cspshare.appspot.com'
##host = 'localhost:9999'
##host = 'http://localhost:9999'
#serv_root = 'http://' + host
#email = 'xxx@gmail.com'
#passwd = 'xxx'
#target = 'http://cspshare.appspot.com/rest/testmodel'
#app_name = "myapp-1.0"
#auth_uri = 'https://www.google.com/accounts/ClientLogin'
#
## Set up a specific logger with our desired output level
#my_logger = logging.getLogger(loggerName)
#my_logger.setLevel(logging.DEBUG)
##
### Add the log message handler to the logger
#log_handler = logging.handlers.WatchedFileHandler(LOG_FILENAME)
#my_logger.addHandler(log_handler)
#
#from google.appengine.api import apiproxy_stub_map
#
#apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
#apiproxy_stub_map.apiproxy.RegisterStub('urlfetch',urlfetch_stub.URLFetchServiceStub())
#
#def tony_run():
#    #authreq_data = urllib.urlencode({ "Email": email, "Passwd":  passwd, "service": "ah", "source":  app_name, "accountType": "HOSTED_OR_GOOGLE" })
#    #result = urllib.urlopen(auth_uri,authreq_data)
#    #result = urlfetch.fetch('https://www.google.com/accounts/ClientLogin', authreq_data, method=urlfetch.POST, follow_redirects=False)
#    
#    #auth_dict = dict([ x.split('=') for x in result.read().split("\n") if (x) ])
#    #auth_dict = dict(for x in result.content.split("\n") x.split("="))
#    #auth_token = auth_dict["Auth"]
#    #print auth_token
#    #serv_args = {}
#    #serv_args['continue'] = target
#    #serv_args['auth'] = auth_token
#    #serv_uri = "%s/_ah/login?%s" % (serv_root, urllib.urlencode(serv_args))
#    #result2 = urlfetch.fetch(serv_uri, follow_redirects=False,method=urlfetch.GET)
#    #result2 = urllib.urlopen(serv_uri)
#    ### here's the cookie which will authenticate future requests
#    #cookie = result2.headers['set-cookie'].split(';')[0]
#    #print cookie
#    
#    # prepare request to cspshare server
#    #cookiejar = cookielib.CookieJar()
#    #request = urllib2.Request(target)
#    #cookiejar.extract_cookies(result2, request) # extract cookie from response, put into request
#    #cookies = cookiejar.make_cookies(result2, request)
#    #cookiejar.set_cookie(cookies[0])
#    #print cookiejar
#    #print cookies
#    
#    #opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
#    #f = opener.open(request)
#    #print f.read()
#    
#    # Now get that file-like object again, remembering to mention the data.
#    #g = urllib.urlopen(auth_uri,authreq_data)
#    
#    #credentials = self.auth_function()
#    
#    # Get auth. token
#    authreq_data = urlencode({ "Email": email, "Passwd":  passwd, "service": "ah", "source": app_name, "accountType": "HOSTED_OR_GOOGLE" })
#    auth_result = urlfetch.fetch(auth_uri,authreq_data,method=urlfetch.POST)
#    auth_dict = dict([ x.split('=') for x in auth_result.content.split("\n") if (x) ])
#    if auth_dict.has_key('Auth'):
#        auth_token = auth_dict["Auth"]
#        print 'auth_token:',auth_token
#        
#        # Get auth.cookie
#        serv_args = {'auth': auth_token, 'continue': target}
#        serv_uri = "%s/_ah/login?%s" % (serv_root, urlencode(serv_args))
#        cookie_result = urlfetch.fetch(serv_uri,follow_redirects=False,method=urlfetch.GET)
#        #print cookie_result.status_code
#        #print cookie_result.content
#        #print cookie_result.headers
#        cookie = cookie_result.headers['set-cookie'].split('=')
#        cookie[1] = cookie[1].strip('; expires')
#        print 'cookie:',cookie
#        
#        # use cookie
#        headers = {'Cookie' : cookie[0]+'='+cookie[1]}
#        result = urlfetch.fetch(target,headers=headers,follow_redirects=False)
#        #print result.status_code
#        print result.content
#        #print result.headers
#    else:
#        pass # bad authentication!
#    #print auth_result.status_code
#    #print auth_result.content
#    #print auth_result.headers
#    
#    
#    
#    # Dev app. server
#    #headers = {'Cookie' : ('dev_appserver_login="%s:True"; Path=/;' % email)}
#    #result = urlfetch.fetch(host,headers=headers,follow_redirects=False)
#    #print result.status_code
#    #print result.content
#    #print result.headers
#
#def myFunc():
#    return (email,passwd)
#
#def appengine_rpc_run():
#    rpcServer = appengine_rpc.HttpRpcServer(host,myFunc,None,app_name,save_cookies=True,auth_tries=5)
#    bla = rpcServer.Send('/')
#    #print bla
#
##test1 = dict(cgi.parse_qsl(g.read()))
##print test1 
##test = urllib.unquote(g.read())
##print test
#
##line = g.readline()
##token = ''
##while line:
##    if line.startswith('Auth'):
##        token = line[5:]
##    line = g.readline()
##
##print token
##print g.info()
##
##if token:
##    url = 'http://cspshare.appspot.com/rest/testmodel'
##    #url = 'http://localhost:9999/rest/testmodel'
##    headers = {'Authorization': 'GoogleLogin auth='+token}
##    
##    #password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
##    #password_mgr.add_password(None, "http://twitter.com/", username, password)
##    #handler = urllib2.HTTPBasicAuthHandler(password_mgr)
##    handler = urllib2.HTTPHandler()
##    opener = urllib2.build_opener(handler)
##    #data = urllib.urlencode({'status' : msg})
##    req = urllib2.Request(url, headers=headers)
##    #print req.has_header('Authorization') 
##    f = opener.open(req)
#
#
#tony_run()
##appengine_rpc_run()